/* File: Open.m - (Interactive) Unix shell version of OpenPanel
 *
 * By: Christopher Lane (lane@sumex-aim.stanford.edu)
 *
 * Date: 10 November 1992
 *
 * Copyright: 1990, 1991 & 1992 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 */

#import <stdlib.h>
#import <getopt.h>
#import <strings.h>
#import <sys/param.h>
#import <appkit/OpenPanel.h>
#import <appkit/Application.h>

#define USAGE "usage: %s [-f file] [-d directory] [-t type [-t type]] [-p prompt] [-T title] [-m] [-c]\n"
#define EXIT_USAGE (2)
#define SEPARATOR "/"

#define MAX_TYPES 64

const char *fullPath(const char *parent, const char *name)
{
	static char buffer[MAXPATHLEN];
	
	if(parent == NULL) return name;
	
	if(strcmp(strcpy(buffer, parent), SEPARATOR) != 0) (void) strcat(buffer, SEPARATOR);
	
	return strcat(buffer, name);
}

void main(int argc, char *argv[])
{
	OpenPanel *panel;
	const char *const *filenames;
	int option, status = EXIT_SUCCESS, ntypes = 0;
	const char *name = NULL, *path = NULL, *types[MAX_TYPES];
	
	NXApp = [Application new];
	panel = [OpenPanel new];
	
	while ((option = getopt(argc, argv, "f:d:t:p:T:mc")) != EOF)
		switch (option) {
		case 'f': name = optarg; break;
		case 'd': path = optarg; break;
		case 't': types[ntypes++] = optarg; break;
		case 'p': [panel setPrompt:optarg]; break;
		case 'T': [panel setTitle:optarg]; break;
		case 'm': [panel allowMultipleFiles:YES]; break;
		case 'c': [panel chooseDirectories:YES]; break;
		default : status = EXIT_USAGE;
		}
	if (optind < argc) status = EXIT_USAGE;
	
	types[ntypes] = NULL;
			
	if (status == EXIT_USAGE) (void) fprintf(stderr, USAGE, [NXApp appName]);
	else {
		int context = [NXApp activateSelf:YES];
	
		if ([panel runModalForDirectory:path file:name types:types]) {
			path = [panel directory];
			for (filenames = [panel filenames]; filenames && *filenames; filenames++)
				(void) puts(fullPath(path, *filenames));
			}
		else status = EXIT_FAILURE;
		
		if (context) (void) [NXApp activate:context];
		}
	
	[panel free];
		
	[NXApp free];
	
	exit(status);
}
